<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/
namespace app\admin\controller\merchant;

use app\admin\controller\Exception;
use app\admin\model\merchant\Image;
use app\admin\model\merchant\Merchant;
use app\admin\model\merchant\StoreInfo;
use app\admin\model\Merchant_account;
use app\admin\model\User;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 商户管理
 *
 * @icon fa fa-circle-o
 */
class Index extends Backend
{

    /**
     * Merchant模型对象
     * @var \app\admin\model\Merchant
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new Merchant();
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }


    /**
     * 基础方法
     * @return string|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add(){
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }



        if (!empty($params['mobile']) && $this->model->where('mobile',$params['mobile'])->find()){
            $this->error('当前手机号已存在');
        }

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            $image = [];
            if ($params['banner_image']){
                $image = explode(',',$params['banner_image']);
                unset($params['banner_image']);
            }
            $result = $this->model->allowField(true)->save($params);
            $insertId = $this->model->getLastInsID();
            Merchant_account::create(['merchant_id'=>$insertId]);
            if (!empty($params['mobile']) && $mobileInfo = User::where('mobile',$params['mobile'])->find()) {

                StoreInfo::create([
                    'merchant_id' => $insertId,
                    'store_id' => 0,
                    'is_manager' => StoreInfo::IS_MANAGER,
                    'user_id' => $mobileInfo['id'],
                    'create_time' => time(),
                ]);

                User::where('id', $mobileInfo['id'])->update(['is_merchant'=>\app\common\model\User::IS_MERCHANT_YES,'merchant_id'=>$insertId]);
                $this->model->where('id', $insertId)->update(['user_id'=>$mobileInfo['id']]);
            }

            if ($image){
                foreach ($image as $v){
                    $imageInsert[] = [
                        'merchant_id'=>$insertId,
                        'url'=>$v,
                        'created_time'=>time(),
                        ];
                }
                if ($imageInsert){
                    $imageModel = new Image();
                    $imageModel->saveAll($imageInsert);
                }
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function edit($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $info = Image::where('merchant_id',$row->id)->select();
        $imageArr = [];
        if ($info){
            foreach ($info as $v){
                $imageArr[] = $v->url;
            }
        }
        $row->banner_image = $imageArr ? implode(',',$imageArr) : '';
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            if (!empty($params['mobile']) && $params['mobile'] != $row->mobile && $this->model->where('mobile',$params['mobile'])->find()){
                $this->error('当前手机号已存在');
            }


            if ($row->status == Merchant::STATUS_NORMAL && $params['status'] == Merchant::STATUS_NORMAL){
                /**
                 * 如果更换用户账户信息，
                 * 1、则需要去除原来账户商户属性特征
                 * 2、删除原来账户商户绑定记录
                 * 3、添加现在用户商户属性
                 * 4、添加现在用户商户绑定记录
                 */
                if ($row->mobile != $params['mobile'] ) {

                    /**
                     * 1、则需要去除原来账户商户属性特征
                     * 2、删除原来账户商户绑定记录
                     */
                    if($mobileInfo = User::where('mobile',$row->mobile)->find()){
                        StoreInfo::where([
                            'merchant_id' => $row->id,
                            'user_id' => $mobileInfo['id'],
                        ])->delete();

                        User::where('mobile',$row->mobile)->update(['is_merchant'=>\app\common\model\User::IS_MERCHANT_NO,'merchant_id'=> 0]);
                    }

                    /**
                     * 3、添加现在用户商户属性
                     * 4、添加现在用户商户绑定记录
                     */
                    if ($mobileInfoNew = User::where('mobile',$params['mobile'])->find()) {

                        StoreInfo::create([
                            'merchant_id' => $row->id,
                            'store_id' => 0,
                            'is_manager' => StoreInfo::IS_MANAGER,
                            'user_id' => $mobileInfoNew['id'],
                            'create_time' => time(),
                        ]);

                        User::where('mobile', $params['mobile'])->update(['is_merchant'=>\app\common\model\User::IS_MERCHANT_YES,'merchant_id'=>$row->id]);
                        $params['user_id'] = $mobileInfoNew['id'];
                    }else{
                        $params['user_id'] = 0;
                    }

                }
            }else if($row->status == Merchant::STATUS_NORMAL && $params['status'] == Merchant::STATUS_UNAVAILABLE){
                if($mobileInfo = User::where('mobile',$row->mobile)->find()){
                    StoreInfo::where([
                        'merchant_id' => $row->id,
                        'user_id' => $mobileInfo['id'],
                    ])->delete();

                    User::where('mobile',$row->mobile)->update(['is_merchant'=>\app\common\model\User::IS_MERCHANT_NO,'merchant_id'=> 0]);
                }
            }else if ($row->status == Merchant::STATUS_NORMAL && $params['status'] == Merchant::STATUS_REJECT){
                $this->error('商户状态不能为拒绝');
            }else if($row->status == Merchant::STATUS_NORMAL && $params['status'] == Merchant::STATUS_WAIT){
                $this->error('商户状态不能为待审核');
            }else if( ($row->status == Merchant::STATUS_WAIT || $row->status == Merchant::STATUS_REJECT || $row->status == Merchant::STATUS_UNAVAILABLE ) && $params['status'] == Merchant::STATUS_NORMAL){
                if ($mobileInfoNew = User::where('mobile',$params['mobile'])->find()) {

                    StoreInfo::create([
                        'merchant_id' => $row->id,
                        'store_id' => 0,
                        'is_manager' => StoreInfo::IS_MANAGER,
                        'user_id' => $mobileInfoNew['id'],
                        'create_time' => time(),
                    ]);

                    User::where('mobile', $params['mobile'])->update(['is_merchant'=>\app\common\model\User::IS_MERCHANT_YES,'merchant_id'=>$row->id]);
                    $params['user_id'] = $mobileInfoNew['id'];
                }else{
                    $params['user_id'] = 0;
                }
            }

            $image = [];
            if ($params['banner_image']){
                $image = explode(',',$params['banner_image']);
                unset($params['banner_image']);
            }
            $result = $row->allowField(true)->save($params);

            if ($image){
                foreach ($image as $v){
                    $imageInsert[] = [
                        'merchant_id'=>$row->id,
                        'url'=>$v,
                        'created_time'=>time(),
                    ];
                }
                if ($imageInsert){
                    $imageModel = new Image();
                    $imageModel->where('merchant_id',$row->id)->delete();
                    $imageModel->saveAll($imageInsert);
                }
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function del($ids=null)
    {

        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
                if ($mobileInfo = User::where('mobile',$item->mobile)->find()) {
                    if (StoreInfo::where('user_id',$mobileInfo['id'])->where('store_id',0)->count() <= 1) {
                        User::where('id',$mobileInfo['id'])->update(['is_merchant'=>\app\common\model\User::IS_MERCHANT_NO]);
                    }
                }

                StoreInfo::where('merchant_id',$item->id)->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }


}
